<script>
import classNames from 'classnames'
import { ConfigConsumerProps } from '@/components/config-provider'
import { Emitter } from '@/mixins'

export default {
  name: 'TagBox',
  mixins: [Emitter],
  inject: {
    configProvider: { default: () => ConfigConsumerProps }
  },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    closable: Boolean,
    validateEvent: {
      type: Boolean,
      default: true
    },
    props: {
      default () {
        return {
          label: 'label',
          value: 'value'
        }
      }
    }
  },
  data () {
    return {}
  },
  computed: {
    labelProp () {
      return this.props.label || 'label'
    },

    valueProp () {
      return this.props.value || 'value'
    }
  },
  methods: {
    handleClose (item) {
      const index = this.value.findIndex(
        tag => tag[this.valueProp] === item[this.valueProp]
      )
      if (index > -1) {
        this.value.splice(index, 1)
      }
      this.$emit('close', item)
    },
    handleClick (item) {
      this.$emit('click', item)
    }
  },
  render () {
    const { $attrs, $props, $slots, labelProp, valueProp } = this

    const tagProps = {
      attrs: {
        ...$attrs
      },
      props: $props
    }

    const getPrefixCls = this.configProvider.getPrefixCls
    const prefixCls = getPrefixCls('tag-box')
    const tagBoxCls = classNames(prefixCls, {
      'has-footer': $slots.footer
    })
    const footerClass = classNames(`${prefixCls}__footer`)
    const footer = $slots.footer ? (
      <div class={footerClass}>{$slots.footer}</div>
    ) : null

    return (
      <div class={tagBoxCls}>
        {this.value.map(tag => (
          <el-tag
            key={tag[valueProp]}
            {...tagProps}
            on-close={() => this.handleClose(tag)}
            on-click={() => this.handleClick(tag)}
          >
            {tag[labelProp]}
          </el-tag>
        ))}
        {footer}
      </div>
    )
  },

  watch: {
    value (val) {
      if (this.validateEvent) {
        this.dispatch('ElFormItem', 'el.form.change', [val])
      }
    }
  }
}
</script>
